package com.atguigu.ucenterservice.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.ucenterservice.entity.UcenterMember;
import com.atguigu.ucenterservice.service.UcenterMemberService;
import com.atguigu.ucenterservice.utils.ConstantWxUtils;
import com.atguigu.ucenterservice.utils.HttpClientUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
@Slf4j
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    /**
     * 1、生成微信扫描二维码
     *
     * @return
     */
    @GetMapping("login")
    public String getWxCode() {
        // 请求微信地址
        String baseUrl ="https://open.weixin.qq.com/connect/qrconnect"
                +"?appid=%s"
                +"&redirect_uri=%s"
                +"&response_type=code"
                +"&scope=snsapi_login"
                +"&state=%s"
                +"#wechat_redirect";

        // 回调地址
        String redirectUri = ConstantWxUtils.WX_REDIRECT_URL;
        try {
            redirectUri = URLEncoder.encode(redirectUri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }

        String url = String.format(baseUrl, ConstantWxUtils.WX_APP_ID, redirectUri, "aqing");

        return "redirect:" + url;
    }

    /**
     * 没有微信的开放平台账号，申请麻烦，使用测试公众号进行开发
     * 换个方式获取用户信息，进行学习
     * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx448138c63d1a82db&redirect_uri=https://chenyeqing.zwjk.com/api/ucenter/wx/getCode&response_type=code&scope=snsapi_userinfo&state=123&#wechat_redirect
     *
     * @param code
     * @param state
     * @param session
     * @return
     */
    @RequestMapping("getCode")
    public String code(String code, String state, HttpSession session) {

        //拿着code，去请求微信固定的地址，得到两个值 access_token 和 openid
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"+
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        //拼接三个参数：id 秘钥 和 code值
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWxUtils.WX_APP_ID
                , ConstantWxUtils.WX_APP_SECRET
                , code);

        //请求上面拼接好的地址，得到两个值 access_token 和 openid
        //使用httpclient【不用浏览器，也能模拟器出浏览器的请求和响应过程】发送请求，得到返回的结果
        String accessTokenInfo = null;
        try {
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo：。。。" +accessTokenInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //从accessTokenInfo中获取出  access_token 和 openid 的值
        //将 accessTokenInfo 转换成 map集合，根据map的key 就可以获取对应的value
        //使用json转换工具
        Gson gson = new Gson();
        HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
        String access_token = (String) mapAccessToken.get("access_token");
        String openid = (String) mapAccessToken.get("openid");

        //判断数据库是否存在相同的微信内容
        UcenterMember member = ucenterMemberService.getMemberByOpenId(openid);

        //如果没有，则为新用户，添加数据库
        if (member == null){

            // 调用微信的获取用户信息
            HashMap resultMap = ucenterMemberService.getUserInfo(openid, access_token);

            String nickname = (String) resultMap.get("nickname");
            String headimgurl = (String) resultMap.get("headimgurl");

            //向数据库插入一条记录
            member = new UcenterMember();
            member.setNickname(nickname);
            member.setAvatar(headimgurl);
            member.setOpenid(openid);
            ucenterMemberService.save(member);
        }

        //使用jwt根据member对象生成token字符串
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());

        //最后，返回首页，通过路径传递token字符串
        return "redirect:http://localhost:3000/?token="+jwtToken;
    }


}
